package com.os.meituan.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
public class WebConfig implements WebMvcConfigurer {
//    @Autowired
//    private ResponseResultInterceptor responseResultInterceptor;

    @Value("${spring.jackson.time-zone}")
    private String timeZone;
    @Value("${spring.jackson.date-format}")
    private String dateFormat;

    @Autowired
    ObjectMapper objectMapper;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
//                .allowedOrigins("http://domain2.com")
                .allowedMethods("GET","POST","PUT", "DELETE")
                .allowCredentials(false)
                .maxAge(3600);
    }

//    @Override
//    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
//
//        // 这句话是为了让包装器ResponseResultHandler在转换string的时候，提前执行类型转换
//        converters.add(0, new MappingJackson2HttpMessageConverter());
//    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.removeIf(c -> c instanceof MappingJackson2HttpMessageConverter); // 重点，删丢其他jar包乱配置的json转换器
        converters.add(new JacksonHttpMessageConverter(timeZone,dateFormat));
//        converters.add(mappingJackson2HttpMessageConverter());
    }

//    @Bean
//    public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
//        MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter =
//                new MappingJackson2HttpMessageConverter();
//
//        //序列化的时候序列对象的所有属性
//        objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
//
//        //反序列化的时候如果多了其他属性,不抛出异常
//        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//
//        //如果是空对象的时候,不抛异常
//        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
//
//        //取消时间的转化格式,默认是时间戳,可以取消,同时需要设置要表现的时间格式
//        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
//
//        var dateFmt = new SimpleDateFormat(dateFormat);
//        dateFmt.setTimeZone(TimeZone.getTimeZone(timeZone));
//
//        objectMapper.setDateFormat(dateFmt);
//
//        mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);
//        return mappingJackson2HttpMessageConverter;
//    }
}
